package com.dbsecurity.config;

import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.Collection;

/**
 * @author jie
 * @date 2019/3/20 0020 -13:58
 */
@Component
public class CustomAccessDecisionManager implements AccessDecisionManager {

    /**
     * 用来判断
     * @param authentication 当前登录的信息
     * @param object FilterInvocation对象
     * @param collection  FilterInvocationSecurityMetadataSource中的getAttribute方法的返回值，即当前请求url所需要的角色
     * @throws AccessDeniedException
     * @throws InsufficientAuthenticationException
     */
    @Override
    public void decide(Authentication authentication,
                       Object object,
                       Collection<ConfigAttribute> collection)
            throws AccessDeniedException, InsufficientAuthenticationException {
        Collection<? extends GrantedAuthority> auths = authentication.getAuthorities();
        //对角色信息对比
        for (ConfigAttribute configAttribute : collection) {
            //如果需要的角色是ROLE_LOGIN，说明当前请求url用户登录后即可访问
            if ("ROLE_LOGIN".equals(configAttribute.getAttribute())
            && authentication instanceof UsernamePasswordAuthenticationToken){
                return;
            }

            //看登录后的用户是否授权
            for (GrantedAuthority authority : auths) {
                //如果用户有权限
                if (configAttribute.getAttribute().equals(authority.getAuthority())){

                    return;
                }
            }
        }
        throw new AccessDeniedException("权限不足");
    }

    @Override
    public boolean supports(ConfigAttribute configAttribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }

}
